import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import {
  Row,
  Col,
  Card,
  Icon,
  Tooltip,
  Form,
  Button,
  Progress,
  Tabs,
  Select,
  Input,
  Table,
  Spin,
  Checkbox,
  Radio,
  message,
  Modal,
} from 'antd';
import styles from './similarAsk.less';
import bulb from '@/assets/medicalKnowledge/灯泡.png';
import { faTshirt } from '@fortawesome/fontawesome-free-solid';
import StandardToAsk from './standardToAsk';

const { Option } = Select;
const Search = Input.Search;
const FormItem = Form.Item;

class AbnormalQ extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ProgressName: '',
      totala: '',
      Selectpd: 'false', // false 为未忽略 true 为已忽略
      Selectcc: false, // 是否忽略传参
      login: false,
      logins: false,
      logines: false,
      searchKeys: '',
      page: 1,
      pageSize: 10,
      similarList: [],
      value: '',
      value1: '',
      judgeMobile: '',
      judgeMobiles: '',
      frompd: 1,
      // 关联参数
      field: 1,
      query: '',
      pageA: '',
      pageSizeA: '',
      id: '', // 上下文参数
      loginjqr: false,
      zuid: '',
      shutRelevance: false,
      showModel1: false,
      numberRadio: 1,
      pageSizetwo: 10,
      pagetwo: 1,
      nodeId: '',
      close: false,
      qaId: '',
      isUpdate: false,
      aALeng: '',
      glLeng: 10,
      questiona: '',
      total: 0,
      fromQaSId: '',
      fromQue: '',
      taskResultId: '',
      taskResultType: null,
      qaListTable: [],
    };
  }

  componentDidMount() {
    const { Selectcc, pageSize, page, searchKeys } = this.state;
    this.similarAskList(Selectcc, pageSize, page, searchKeys);
  }

  componentDidUpdate() {}

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.ProgressName !== this.state.ProgressName) {
      this.setState({ ProgressName: nextProps.ProgressName });
    };
    if (nextProps.ProgressName == 2) {
      // 列表清空
      this.setState({
        Selectpd: 'false',
        similarList: [],
        ProgressName: nextProps.ProgressName,
        totala: 0,
      });
      this.props.totala2(0);
    };
    if (nextProps.ProgressName == 1) {
      // 恢复数据
      if (this.state.ProgressName !== nextProps.ProgressName) {
        this.setState({ page: 1, pageSize: 10, searchKeys: '' }, () => {
          const { Selectcc, pageSize, page, searchKeys } = this.state;
          this.similarAskList(Selectcc, pageSize, page, searchKeys);
        });
        this.props.totala2(this.state.totala);
        this.setState({ ProgressName: nextProps.ProgressName });
      }
    }
  }

  SelectValue = value => {
    if (value === 'false') {
      this.setState({ Selectcc: false }, () => {
        const { Selectcc, pageSize, page, searchKeys } = this.state;
        this.similarAskList(false, pageSize, page, searchKeys);
      });
    };
    if (value === 'true') {
      this.setState({ Selectcc: true }, () => {
        const { Selectcc, pageSize, page, searchKeys } = this.state;
        this.similarAskList(true, pageSize, page, searchKeys);
      });
    };
  };

  append = item => {
    const { value, value1, judgeMobile, judgeMobiles } = this.state;
    if (judgeMobile === item.questions[value] || judgeMobiles === item.stds[value1]) {
      let from = {};
      from.ques = item.questions[value];
      from.sid = item.sids[value];
      let toStdId = item.sids[value1];
      this.setState({ login: true });
      const { dispatch, currentUser } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'medicalKnowledge/movingSimilarQuestions',
          payload: { from, toStdId },
          callback: res => {
            if (res.statue === 'success') {
              message.success(`${res.msg}`);
            };
            this.setState({ login: false, }, () => {
              const { Selectcc, pageSize, page, searchKeys } = this.state;
              this.similarAskList(Selectcc, pageSize, page, searchKeys); // 刷新页面
            });
          },
        });
      });
    } else {
      message.error('无效的移动操作');
    }
  };

  delAbnormalQ = item => {
    // 删除相似问
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'medicalKnowledge/deleteAbnormalQuestion',
        payload: { id: item.id, question: item.question, qaId: item.qaId },
        callback: res => {
          this.StandardToAsk.cancelModal();
          message.success(`${res.msg}`);
          this.setState({ login: false, }, () => {
            const { Selectcc, pageSize, page, searchKeys } = this.state;
            this.similarAskList(Selectcc, pageSize, page, searchKeys);
          });
        },
      });
    });
  };

  deleteTable = item => {
    if (item.type == 1) {
      this.StandardToAsk.openModal('delAbnormalQ', item);
    } else {
      this.delAbnormalQ(item);
    }
  };

  iose = item => {
    const { Selectcc } = this.state;
    if (Selectcc) {
      this.ignore(0, item.id);
    };
    if (Selectcc === false) {
      this.ignore(1, item.id);
    };
  };

  ignore = (a, b) => {
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'medicalKnowledge/ignoreAbnormalQuestion',
        payload: { ignore: a, id: b },
        callback: res => {
          if (res.statue === 'success') {
            message.success(`${res.msg}`);
          };
          this.setState({ login: false, }, () => {
            const { Selectcc, pageSize, page, searchKeys } = this.state;
            this.similarAskList(Selectcc, pageSize, page, searchKeys);
          });
        },
      });
    });
  };

  // 异常问列表
  similarAskList = (isIgnore, limit = 10, page = 1, searchKeys) => {
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'medicalKnowledge/getAbnormalList',
        payload: {
          isIgnore: isIgnore ? 1 : 0,
          size: limit,
          current: page,
          question: searchKeys,
          tenantId: currentUser.tenantId,
        },
        callback: res => {
          this.setState({ login: false, similarList: res.records, totala: res.total, }, () => {
            this.props.totala2(this.state.totala);
          });
        },
      });
    });
  };

  pageWay = a => {
    this.setState({ page: a }, () => {
      const { Selectcc, pageSize, page, searchKeys } = this.state;
      this.similarAskList(Selectcc, pageSize, page, searchKeys);
    });
  };

  onShowSizepageWay = (a, b) => {
    this.setState({ page: a, pageSize: b }, () => {
      const { Selectcc, pageSize, page, searchKeys } = this.state;
      this.similarAskList(Selectcc, pageSize, page, searchKeys);
    });
  };

  allIgnore = () => {
    // 全部忽略
    this.setState({ logines: true, }, () => {
      const { Selectcc } = this.state;
      if (Selectcc) {
        this.ignoreAll(0);
      };
      if (Selectcc === false) {
        this.ignoreAll(1);
      };
    });
  };

  ignoreAll = a => {
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'medicalKnowledge/allIgnoreAbnormalQuestion',
        payload: { ignore: a },
        callback: res => {
          if (res.statue === 'success') {
            message.success(`${res.msg}`);
          };
          this.setState({ login: false, logines: false, }, () => {
            const { Selectcc, pageSize, page, searchKeys } = this.state;
            this.similarAskList(Selectcc, pageSize, page, searchKeys);
          });
        },
      });
    });
  };

  //  关联方法
  handleOpen = row => {
    this.props.form.setFields({ businessName: '' });
    this.setState({ question: row.question, query: '' }, () => {
      this.AnswerRelevance(
        this.state.question,
        this.state.field,
        this.state.query,
        1,
        10
      );
      this.setState({
        showModel1: true,
        fromQaSId: row.sid,
        fromQue: row.question,
        taskResultId: row.id,
        taskResultType: row.type,
      });
    });
  };

  // 获取关联列表数据
  AnswerRelevance = (question, field, query, page, pageSize) => {
    this.setState({ logins: true });
    let that = this;
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'medicalKnowledge/fakeAnswerRelevanceData',
      payload: { question, type: field, search: query, current: page, size: pageSize },
      callback: res => {
        let total = res.records;
        total.forEach((item, index) => {
          item['key'] = index;
        });
        that.setState({
          total2: res.total,
          qaListTable: total,
          logins: false,
          aALeng: res.size,
          glLeng: Number(res.size),
        });
      },
    });
  };

  handleSubmitComment = current => {
    this.AnswerRelevance(
      this.state.question,
      this.state.field,
      this.state.query,
      current,
      this.state.pageSizetwo
    );
  };

  handleSubmitComments = (a, b) => {
    this.setState({ pageSizetwo: b });
    this.AnswerRelevance(
      this.state.question,
      this.state.field,
      this.state.query,
      a,
      b
    );
  };

  // 搜索问题
  onFromA = val => {
    this.setState({
      pagetwo: 1,
      pageSizetwo: 10,
      field: val,
    });
    setTimeout(() => {
      this.AnswerRelevance(
        this.state.question,
        this.state.field,
        this.state.query,
        1,
        10
      );
    });
  };

  // 搜索内容
  onFrom = val => {
    this.setState(
      {
        pagetwo: 1,
        pageSizetwo: 10,
        query: val,
      },
      () => {
        this.AnswerRelevance(
          this.state.question,
          this.state.field,
          this.state.query,
          1,
          10
        );
      }
    );
  };

  relationQa = item => {
    this.setState({ shutRelevance: false });
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'medicalKnowledge/addToOtherQa',
      payload: { id: item.id, qaId: item.qaId, question: item.question, qaType: item.qaType, },
      callback: res => {
        // console.log(res);
        this.StandardToAsk.cancelModal();
        message.success(`${res.msg}`);
        this.setState({ showModel1: false });
        const { Selectcc, pageSize, page, searchKeys } = this.state;
        this.similarAskList(Selectcc, pageSize, page, searchKeys);
      },
    });
  };

  handleDelete = item => {
    const { taskResultType, taskResultId } = this.state;
    let qaType;
    switch (item.qaType) {
      case 1:
        qaType = 'qa';
        break;
      case 2:
        qaType = 'atlasNode';
        break;
      case 3:
        qaType = 'dialog';
        break;
    };
    let data = {
      id: taskResultId,
      qaId: item.id,
      question: this.state.question,
      qaType,
    };
    if (taskResultType == 1) {
      this.StandardToAsk.openModal('relationAbnormalQ', data);
    } else {
      this.relationQa(data);
    }
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const columns1 = [
      {
        title: '问题',
        dataIndex: 'basicQuestion',
      },
      {
        title: '分类',
        dataIndex: 'categoryNamePath',
      },
      {
        title: '操作',
        render: (text, item) => {
          return (
            <div className={styles.pb}>
              <div
                className={styles.buttongx}
                onClick={text => {
                  this.handleDelete(item);
                }}
              >
                {/* <MyIcon  type="icon-bi" /> */}
                <span>
                  <Icon size="small" type="link" style={{ marginRight: 5 }} />
                </span>
                <span>关联</span>
              </div>
            </div>
          );
        },
      },
    ];
    const columns = [
      {
        title: '异常问法',
        width: 'calc(30vw)',
        dataIndex: 'question',
        render: item => {
          return <div dangerouslySetInnerHTML={{ __html: item }}></div>;
        },
      },
      {
        title: '所属问题的其它问法',
        dataIndex: 'reference',
        width: 'calc(30vw)',
        render: (reference, items) => {
          return (
            <Row>
              {reference.map((item, index) => {
                return (
                  <Row style={{ marginBottom: 10 }}>
                    <Col span={24}>{item}</Col>
                  </Row>
                );
              })}
            </Row>
          );
        },
      },
      {
        title: '操作',
        width: 'calc(15vw)',
        dataIndex: '',
        render: (text, item) => {
          if (this.state.Selectcc) {
            // 已忽略
            return (
              <div className={styles.flexBj}>
                <Button
                  style={{ marginRight: 10, marginBottom: 4 }}
                  icon="eye-invisible"
                  size="small"
                  onClick={() => {
                    this.iose(item);
                  }}
                  type="primary"
                >
                  恢复
                </Button>
                <div
                  style={{ marginRight: 10, marginBottom: 4 }}
                  className={styles.buttongl}
                  onClick={() => {
                    this.deleteTable(item);
                  }}
                >
                  <span>
                    <Icon size="small" type="delete" style={{ marginRight: 5 }} />
                  </span>
                  <span>删除</span>
                </div>
                <Button
                  type="primary"
                  icon="link"
                  size="small"
                  onClick={() => this.handleOpen(item)}
                >
                  关联
                </Button>
              </div>
            );
          } else {
            return (
              <div className={styles.flexBj}>
                <div className="zdyButtonA">
                  {' '}
                  <Button
                    style={{ marginRight: 10, marginBottom: 4 }}
                    icon="eye-invisible"
                    size="small"
                    onClick={() => {
                      this.iose(item);
                    }}
                    type="primary"
                  >
                    忽略
                  </Button>
                </div>
                <div
                  style={{ marginRight: 10, marginBottom: 4 }}
                  className={styles.buttongl}
                  onClick={() => {
                    this.deleteTable(item);
                  }}
                >
                  <span>
                    <Icon size="small" type="delete" style={{ marginRight: 5 }} />
                  </span>
                  <span>删除</span>
                </div>
                <div className="zdyButtonA">
                  <Button
                    type="primary"
                    icon="link"
                    size="small"
                    onClick={() => this.handleOpen(item)}
                  >
                    关联
                  </Button>
                </div>
              </div>
            );
          }
        },
      },
    ];
    return (
      <Suspense fallback={<PageLoading />}>
        <div>
          <div className={styles.toptit}>
            {this.state.Selectcc ? (
              <div className="zdyButtonA">
                <Button
                  onClick={this.allIgnore}
                  type="primary"
                  icon="eye-invisible"
                  loading={this.state.logines}
                >
                  全部恢复
                </Button>
              </div>
            ) : (
              <div className="zdyButtonA">
                <Button
                  onClick={this.allIgnore}
                  type="primary"
                  icon="eye-invisible"
                  loading={this.state.logines}
                >
                  全部忽略
                </Button>
              </div>
            )}
            <div>
              {getFieldDecorator('coreword1', {
                initialValue: this.state.Selectpd,
              })(
                <Select style={{ width: 120 }} onChange={this.SelectValue}>
                  <Option value="false">未忽略</Option>
                  <Option value="true">已忽略</Option>
                </Select>
              )}
              <span>&#12288;</span>
              {getFieldDecorator('coreword2', {
                initialValue: '',
              })(
                <Search
                  placeholder="多个关键词用空格隔开"
                  onSearch={value => {
                    this.setState({ searchKeys: value, page: 1 }, () => {
                      const { Selectcc, pageSize, page, searchKeys } = this.state;
                      this.similarAskList(Selectcc, pageSize, page, searchKeys);
                    });
                  }}
                  style={{ width: 324 }}
                />
              )}
            </div>
          </div>
          <Spin spinning={this.state.login}>
            <Table
              className="zdyTable"
              style={{ padding: '20px 0px 0px 0px' }}
              columns={columns}
              dataSource={this.state.similarList} // 数据
              // onChange={this.handleChange}
              pagination={{
                // 分页
                total: this.state.totala,
                pageSize: this.state.pageSize, // 显示几条一页
                current: this.state.page, // 当前页
                showSizeChanger: true, // 是否显示可以设置几条一页的选项
                showQuickJumper: true,
                onChange: this.pageWay,
                onShowSizeChange: this.onShowSizepageWay,
              }}
            />
          </Spin>

          {/* 关联组件 */}
          <Modal
            style={{ top: 60 }}
            width={'calc(70vw)'}
            className={styles.overa}
            title="添加关联知识点"
            visible={this.state.showModel1}
            footer={null}
            onCancel={() => {
              this.setState({
                showModel1: false,
                field: 1,
              });
            }}
            onOk={() => {
              // 确定方法不开出去
              this.setState({
                showModel1: false,
                field: 1,
              });
            }}
          >
            <Form layout="inline" style={{ paddingBottom: 20 }}>
              <FormItem style={{ marginLeft: 20 }}>
                <Select
                  defaultValue={this.state.numberRadio}
                  style={{ width: 160 }}
                  onChange={this.onFromA}
                >
                  <Option value={1}>问答知识点</Option>
                  <Option value={2}>导图知识点</Option>
                  <Option value={3}>多轮会话</Option>
                </Select>
              </FormItem>
              <FormItem>
                {getFieldDecorator('businessName', {
                  initialValue: '',
                })(
                  <Search
                    placeholder="请输入搜索内容"
                    onSearch={value => {
                      this.onFrom(value);
                    }}
                    style={{ width: 320 }}
                  />
                )}
              </FormItem>
            </Form>
            <Spin spinning={false}>
              <Table
                // className={styles.over}
                // bordered
                columns={columns1}
                scroll={{ y: 500 }}
                dataSource={this.state.qaListTable}
                pagination={{
                  // 分页
                  total: this.state.total2, // 数据总数量
                  pageSize: this.state.glLeng, // 显示几条一页
                  defaultPageSize: this.state.pagetwo, // 当前页
                  showQuickJumper: true,
                  onChange: this.handleSubmitComment,
                  onShowSizeChange: this.handleSubmitComments,
                }}
              />
            </Spin>
          </Modal>
          <StandardToAsk
            onRef={ref => (this.StandardToAsk = ref)}
            delAbnormalQ={this.delAbnormalQ}
            relationQa={this.relationQa}
          />
        </div>
      </Suspense>
    );
  }
}

export default connect(({ user }) => ({
  // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(AbnormalQ));
